package com.real8.romemp.client.activity;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.real8.romemp.client.ClientFactory;
import com.real8.romemp.client.GameConstants;
import com.real8.romemp.client.place.FeedPlace;
import com.real8.romemp.client.place.PoliticalPlace;
import com.real8.romemp.client.ui.FeedView;
import com.real8.romemp.client.ui.FeedView.Presenter;
import com.real8.romemp.shared.GameData;

public class FeedActivity extends AbstractActivity implements Presenter {
	private final ClientFactory clientFactory;
	private FeedView view;

	public FeedActivity(FeedPlace place, ClientFactory clientFactory) {
		this.clientFactory = clientFactory;
	}

	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		view = clientFactory.getFeedView();
		if (view != null) {
			view.setPresenter(this);

			// prepare view
			view.hideAll();

			// determine available food
			final GameData gameData = clientFactory.getGameData();
			int FV = Random.nextInt(40) + 85;
			int ML_localMerchantShips = gameData.getML_localMerchantShips();
			int gainedFood = ML_localMerchantShips * FV / 100;
			int availableFood = gameData.getFS_foodReserve() + gainedFood;

			// show available food
			view.showFoodAvailable(ML_localMerchantShips, gainedFood, gameData
					.getFS_foodReserve(), availableFood);

			// determine food need
			availableFood -= gameData.getFR_foodNeed();
			gameData.setFS_foodReserve(availableFood);

			// check enough food
			if (availableFood < 0) {
				// determine & set extra cost
				final int extraFoodCost = -2000 * availableFood;
				gameData.setTR_treasury(gameData.getTR_treasury()
						- extraFoodCost);
				gameData.setVF_popularity(gameData.getVF_popularity() - 2
						* availableFood);
				gameData.setFS_foodReserve(0);

				// show insufficient food
				view.showInsufficientFood(-availableFood);

				// delay
				Timer timer = new Timer() {
					@Override
					public void run() {
						// show extra food
						view.showExtraFoodCost(extraFoodCost);

						// show continue
						view.showContinue();
					}
				};
				timer.schedule(GameConstants.DELAY_6000);

			} else {
				// show enough food
				view.showEnoughFood();

				// show continue
				view.showContinue();
			}

			// set widget
			containerWidget.setWidget(view.asWidget());
		}
	}

	@Override
	public void onContinue() {
		goToNextPlace();
	}

	private void goToNextPlace() {
		clientFactory.getPlaceController().goTo(new PoliticalPlace());
	}
}
